package com.oversea.util.page;

/**
 * @author Power
 * 
 */
public final class PageUtil {
	private PageUtil() {
	}

	/**
	 * Use the origin page to create a new page
	 * 
	 * @param page
	 *            page object
	 * @param totalRecords
	 *            total records
	 * @return new page object
	 */
	public static Page createPage(Page page, int totalRecords) {
		return createPage(page.getEveryPage(), page.getCurrentPage(), totalRecords);
	}

	/**
	 * the basic page utils not including exception handler
	 * 
	 * @param everyPage
	 *            the number of every page
	 * @param currentPage
	 *            the number of current page
	 * @param totalRecords
	 *            the total Records of the query
	 * @return page page object
	 */
	public static Page createPage(int everyPage, int currentPage, int totalRecords) {
		int everyPageNew = getEveryPage(everyPage);
		int totalPage = getTotalPage(everyPageNew, totalRecords);
		int currentPageNew = getCurrentPage(currentPage);
		if (currentPageNew > totalPage) {
			currentPageNew = totalPage;
		}
		int beginIndex = getBeginIndex(everyPageNew, currentPageNew);
		boolean hasNextPage = hasNextPage(currentPageNew, totalPage);
		boolean hasPrePage = hasPrePage(currentPageNew);

		return new Page(hasPrePage, hasNextPage, everyPageNew, totalPage, currentPageNew, beginIndex, totalRecords);
	}

	private static int getEveryPage(int everyPage) {
		return everyPage == 0 ? 10 : everyPage;
	}

	private static int getCurrentPage(int currentPage) {
		return currentPage == 0 ? 1 : currentPage;
	}

	private static int getBeginIndex(int everyPage, int currentPage) {
		return (currentPage - 1) * everyPage;
	}

	private static int getTotalPage(int everyPage, int totalRecords) {
		int totalPage = 0;

		if (totalRecords % everyPage == 0) {
			totalPage = totalRecords / everyPage;
		} else {
			totalPage = totalRecords / everyPage + 1;
		}

		return totalPage;
	}

	private static boolean hasPrePage(int currentPage) {
		return currentPage == 1 ? false : true;
	}

	private static boolean hasNextPage(int currentPage, int totalPage) {
		return currentPage == totalPage || totalPage == 0 ? false : true;
	}

}
